package pratica06.dao;

import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;

/**
 *
 * @author a100101
 */
public class ConnectBD {

    private static ConnectBD instance = null;
    private Connection conn;

    private ConnectBD() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        conn = DriverManager.getConnection("jdbc:mysql://localhost/banco_dados?user=root&password=r4gn4r0k");
    }

    public static ConnectBD getInstance() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
        if (instance == null) {
            instance = new ConnectBD();
        }
        return instance;
    }

    public Connection getConnection() {
        return conn;
    }

    public static Statement getStatement() {
        Statement st = null;
        try {
            st = ConnectBD.getInstance().getConnection().createStatement();
        } catch (ClassNotFoundException ex) {
            JOptionPane.showMessageDialog(null, "Classe de driver de conexao nao encontrada!", "Erro na aplicacao", JOptionPane.ERROR_MESSAGE);
        } catch (InstantiationException ex) {
            JOptionPane.showMessageDialog(null, "Problema na instanciacao da classe de driver de conexao nao encontrada!", "Erro na aplicacao", JOptionPane.ERROR_MESSAGE);
        } catch (IllegalAccessException ex) {
            JOptionPane.showMessageDialog(null, "Acesso ilegal no banco de dados!", "Erro na aplicacao", JOptionPane.ERROR_MESSAGE);
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Erro em comando sql!\n" + ex.getMessage(), "Erro na aplicacao", JOptionPane.ERROR_MESSAGE);
        }
        return st;
    }

    public static ResultSet executeQuery(String query) {
        ResultSet rs = null;
        try {
            rs = ConnectBD.getStatement().executeQuery(query);
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Erro em comando sql!\n" + ex.getMessage(), "Erro na aplicacao", JOptionPane.ERROR_MESSAGE);
        }
        return rs;
    }

    public static int executeNonQuery(String query) {
        int result = 0;
        try {
            result = ConnectBD.getStatement().executeUpdate(query);
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Erro em comando sql!\n" + ex.getMessage(), "Erro na aplicacao", JOptionPane.ERROR_MESSAGE);
            //ex.printStackTrace();
        }
        return result;
    }
}
